package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {

        //获取手机号
        String phone = user.getPhone();
        //查看redis中是否含有密码，如果redis中含有密码，则提示用户不能重复获取验证码
        if (redisTemplate.hasKey(phone)) {
            return R.error("短信验证码已发送，不能重复获取");
        }
        if (!StringUtils.isEmpty(phone)) {
            //随机生成四位验证码
            //String code = ValidateCodeUtils.generateValidateCode(4).toString();
            String code = "1234";
            log.info("验证码为：{}", code);
            //调用阿里云提供的短信服务发送短信
            // SMSUtils.sendMessage("模板","",phone,code);

            /*//将验证码存入session中
            session.setAttribute(phone, code);*/
            //将验证码保存到redis中，过期时间为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.HOURS);
            return R.success("短信发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 登录
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String string = map.get("code").toString();
        /*//获取session中的验证码
        Object code = session.getAttribute(phone);*/

        //从redis中获取验证码
        Object code = redisTemplate.opsForValue().get(phone);
        //校验验证码，比对session中的验证码和用户输入的验证码
        if (string.equals(code) && code != null) {
            //如果比对成功，则登录成功
            //判断用户是否为新用户，为新用户则注册
            LambdaQueryWrapper<User> userlqw = new LambdaQueryWrapper<>();
            userlqw.eq(User::getPhone, phone);
            User user = userService.getOne(userlqw);
            //如果user为空，则为新用户，添加到数据库中
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            //登录成功，删除redis中的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登陆失败");
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("loginout")
    public R<String> loginout() {

        httpServletRequest.getSession().removeAttribute("user");
        return R.success("退出登录成功");

    }
}